package cn.nju.sirx.util;

import java.io.File;
import java.io.IOException;

/**
 * Utility to handle file operations.
 * 
 * @author SirX
 * @version 1.0
 */
public class FileUtil {

    /**
     * Create a file with the given path. e.g. "somedir/somefile"
     * 
     * @param filePath the file path including directory and file name
     * @return a file instance if created successfully, or an IO exception will
     *         be thrown
     * @throws IOException when IO exception occurs
     */
    public static File createFile(String filePath) throws IOException {
        filePath = filePath.replace('\\', '/');
        int i = filePath.lastIndexOf('/');
        if (i >= 0) {
            File dir = new File(filePath.substring(0, i));
            if (!dir.exists() && !dir.mkdirs()) {
                throw new IOException(String.format("failed to create directory \"%s\"", dir));
            }
        }
        File file = new File(filePath);
        if (!file.exists() && !file.createNewFile()) {
            throw new IOException(String.format("failed to create file \"%s\"", filePath));
        }
        return file;
    }

}
